package cn.gson.school.service.jiaoxue;

import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.gson.school.dao.jiaoxue.ZuoYeDao;
import cn.gson.school.dao.jiaoxue.ZuoYeTitleDao;
import cn.gson.school.entity.jiaoxue.TitleEntity;
import cn.gson.school.entity.jiaoxue.ZuoYeTitleEntity;
import cn.gson.school.mappers.jiaoxue.ZuoYeMappers;

@Service
public class ZuoYeService {

	@Autowired
	private ZuoYeDao zuoYeDao;

	private Random random = new Random();

	@Autowired
	private ZuoYeMappers zuoyeMappers;

	@Autowired
	private ZuoYeTitleDao zuoyeTitleDao;

	public void index(String count, Long zuoyeId,String type,Long chapterId) {
		int optionCount = Integer.valueOf(count);
		List<TitleEntity> title1 = zuoyeMappers.chaxunTiMu(type,Long.toString(chapterId));// 查询所有的选择题
		List<TitleEntity> someTitle1 = null;
		if (type=="选择题") {
			someTitle1= zuoyeMappers.cx1(zuoyeId);// 查询布置的选择题
		}else if (type=="判断题") {
			someTitle1= zuoyeMappers.cx2(zuoyeId);// 查询布置的判断题
		}else if (type=="代码题") {
			someTitle1= zuoyeMappers.cx3(zuoyeId);// 查询布置的代码题
		}
		
		// 获取选择题中的集合长度
		int size1 = title1.size();
		// 获取已经布置了的作业集合长度
		int sizeSome = someTitle1.size();
		// 遍历整个items数组
		int neirong1 = Integer.valueOf(count);// 获取前台接受的选择题的数量值
		if (neirong1 > sizeSome) {// 前台输入的选择题数量大于后台已经布置的了
			int cha = neirong1 - sizeSome;
			for (int i = 0; i < cha; i++) {
				int myRand = random.nextInt(size1);
				ZuoYeTitleEntity zuoYeTitleEntity = new ZuoYeTitleEntity();
				zuoYeTitleEntity.setZuoyeId(zuoyeId);
				zuoYeTitleEntity.setTitleId(title1.get(myRand).getTitleId());
				zuoyeTitleDao.save(zuoYeTitleEntity);
			}
		} else if (neirong1 < sizeSome) {// 前台输入的选择题数量小于后台已经布置的了
			// 计算要少多少个题目
			int cha = sizeSome - neirong1;
			for (int i = 0; i < cha; i++) {
				//int myRand = random.nextInt(sizeSome);
				List<ZuoYeTitleEntity> zuoYeTitleEntity = zuoyeTitleDao
						.findByTitleId(someTitle1.get(i).getTitleId());
				zuoyeTitleDao.delete(zuoYeTitleEntity.get(0).getId());
			}
		}
	}
	
	public void index2(String count,String type, Long zuoyeId,Long chapterId) {
		//添加
		List<TitleEntity> title1=zuoyeMappers.chaxunTiMu(type,chapterId.toString());
		//获取题目类型的集合长度
		int size1=title1.size();
		 // 遍历整个items数组  
		int neirong1=Integer.valueOf(count);
        for (int i = 0; i < neirong1; i++) {  
            ZuoYeTitleEntity zuoYeTitleEntity=new ZuoYeTitleEntity();
            zuoYeTitleEntity.setZuoyeId(zuoyeId);
            zuoYeTitleEntity.setTitleId(title1.get(i).getTitleId());
            zuoyeTitleDao.save(zuoYeTitleEntity);
        }      
	}

}
